<template>
  <view class="container">
    <!-- Logo 区域 -->
    <view class="logo-container">
      <image src="/static/images/logo.png" mode="aspectFit" class="logo"></image>
      <text class="app-name">农检通</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <u-form :model="form" ref="uForm" labelPosition="left" labelWidth="160rpx">
        <u-form-item label="手机号码">
          <u-input v-model="form.phone" placeholder="请输入手机号码" />
        </u-form-item>

        <u-form-item label="输入密码">
          <u-input v-model="form.password" type="password" placeholder="请输入密码" />
        </u-form-item>

        <u-button
          type="success"
          @click="handleLogin"
          :loading="loading"
          style="width: 100%; margin-top: 60rpx;"
        >
          登录
        </u-button>

        <!-- 注册/忘记密码链接 -->
        <view class="link-row">
          <u-text text="新用户注册" @click="switchTo('register')" color="#3cc51f" size="28rpx"></u-text>
          <u-text text="忘记/修改密码" @click="switchTo('forgetpassword')" color="#3cc51f" size="28rpx"></u-text>
        </view>

        <!-- 用户协议勾选框 -->
        <u-form-item label="" :border="false">
          <u-checkbox-group @change="onAgreeChange">
            <view class="agree-wrapper">
              <!-- 复选框 -->
              <u-checkbox
                v-model="agree"
                name="agree"
                size="24rpx"
                activeColor="#3cc51f"
                :customStyle="{ 'margin-right': '12rpx' }"
              ></u-checkbox>
              <!-- 协议文字（独立显示，确保可见） -->
              <text class="policy-text">我已阅读并同意《用户协议及隐私政策》</text>
            </view>
          </u-checkbox-group>
        </u-form-item>
      </u-form>
    </view>
  </view>
</template>

<script>
import { post } from '@/utils/request';
import md5 from 'blueimp-md5';
import { useUserStore } from '@/store/user';

export default {
  data() {
    return {
      loading: false,
      form: {
        phone: '',
        password: ''
      },
      agree: false // 默认不勾选，必须用户手动同意
    };
  },
  methods: {
    // 监听 checkbox 变化
    onAgreeChange(val) {
      this.agree = val.includes('agree');
    },

    // 切换页面
    switchTo(page) {
      uni.navigateTo({ url: `/pages/njt/auth/${page}` });
    },

    // 登录处理
    async handleLogin() {
      // 1. 检查是否同意协议
      if (!this.agree) {
        uni.showToast({
          title: '请先同意用户协议',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      const { phone, password } = this.form;

      // 2. 检查表单数据
      if (!phone || !password) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' });
        return;
      }

      if (!/^1[3-9]\d{9}$/.test(phone)) {
        uni.showToast({ title: '手机号格式错误', icon: 'none' });
        return;
      }

      this.loading = true;

      try {
        const res = await post('/nongjt/userAuth/login', {
          mobilePhone: phone,
          password: md5(password)
        });

        if (res.code === 200) {
          console.log('登录返回：', res);
          const userStore = useUserStore();
          userStore.setUser({
            token: res.token,
            user: res.user,
            role: res.role
          });

          uni.showToast({ title: '登录成功' });

          // 跳转首页（根据角色）
          if (res.role === 'supervisor') {
            uni.reLaunch({ url: '/pages/njt/supervisor/supervisorHome/supervisorHome' });
          } else {
            uni.reLaunch({ url: '/pages/njt/user/UserHome' });
          }
        } else {
          uni.showToast({ title: res.msg || '登录失败', icon: 'none' });
        }
      } catch (err) {
        uni.showToast({ title: err.msg || '请求失败', icon: 'none' });
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 80rpx 0;
  gap: 10rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
}

.app-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #3cc51f;
}

.form-container {
  width: 100%;
  max-width: 600rpx;
  padding: 0 30rpx;
}

.link-row {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
  font-size: 28rpx;
}

/* 协议区域布局 */
.agree-wrapper {
  display: flex;
  align-items: center;
  margin-top: 40rpx;
  font-size: 26rpx;
}

.policy-text {
  color: #666;
  font-size: 26rpx;
}
</style>